package com.example.ourradio;


import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 * A fragment representing a list of Items.
 * <p />
 * Large screen devices (such as tablets) are supported by replacing the
 * ListView with a GridView.
 * <p />
 * Activities containing this fragment MUST implement the {@link Callbacks}
 * interface.
 */
public class FeedFragment extends Fragment implements
		AbsListView.OnItemClickListener {
	private FeedTab mTab;
	
	private OnFragmentInteractionListener mListener;

	/**
	 * The fragment's ListView/GridView.
	 */
	private AbsListView mListView;

	/**
	 * The Adapter which will be used to populate the ListView/GridView with
	 * Views.
	 */
	private ListAdapter mAdapter;
	
	private String mAccessToken = null;

	static FeedFragment newInstance(FeedTab tab) {
		FeedFragment frag = new FeedFragment();
		
		// Supply position input as an argument.
        Bundle args = new Bundle();
        args.putSerializable("tab", tab);
        frag.setArguments(args);

        return frag;	
    }
	
	/**
	 * Mandatory empty constructor for the fragment manager to instantiate the
	 * fragment (e.g. upon screen orientation changes).
	 */
	public FeedFragment() {
	}
	
	private FeedActivity getFeedActivity() {
		Activity activity = getActivity();
		if (activity instanceof FeedActivity) {
			return (FeedActivity)activity;
		} 
		return null;
	}
	
	private Feed getContents() {
		FeedActivity activity = getFeedActivity();
		if (activity != null) {
			return activity.getContents();
		} else {
			return new Feed();
		}
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mTab = (FeedTab) (
			getArguments() != null ? 
			getArguments().getSerializable("tab") : 
				FeedTab.FEED
		);

		mAdapter = new ArrayAdapter<Feed.FeedItem>(
			getActivity(),
			android.R.layout.simple_list_item_1, 
			android.R.id.text1,
			getContents().mItems
		);
	}

    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_feed, container, false);

        // Set the adapter
		mListView = (AbsListView) view.findViewById(android.R.id.list);
		((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);

		// Set OnItemClickListener so we can be notified on item clicks
		mListView.setOnItemClickListener(this);

		loadPage();    
		
		return view;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mListener = (OnFragmentInteractionListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnFragmentInteractionListener");
		}
		// Restore preferences
        SharedPreferences settings = 
        	activity.getSharedPreferences(Utils.PREFS_NAME, 0);
        mAccessToken = settings.getString(Utils.OAUTH_TOKEN, null);	
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mListener = null;
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (null != mListener) {
			mListener.onItemClick(position);
		}
	}

	/**
	 * The default content for this Fragment has a TextView that is shown when
	 * the list is empty. If you would like to change the text, call this method
	 * to supply the text it should use.
	 */
	public void setEmptyText(CharSequence emptyText) {
		View emptyView = mListView.getEmptyView();

		if (emptyText instanceof TextView) {
			((TextView) emptyView).setText(emptyText);
		}
	}

	/**
	 * This interface must be implemented by activities that contain this
	 * fragment to allow an interaction in this fragment to be communicated to
	 * the activity and potentially other fragments contained in that activity.
	 * <p>
	 * See the Android Training lesson <a href=
	 * "http://developer.android.com/training/basics/fragments/communicating.html"
	 * >Communicating with Other Fragments</a> for more information.
	 */
	public interface OnFragmentInteractionListener {
		public void onItemClick(int position);
		public void onLoadCompletion(Feed feed, FeedTab tab);
	}
	
	// Uses AsyncTask subclass to download the JSON feed.
    public void loadPage() {
    	FeedActivity activity = getFeedActivity();
    	if (activity != null) {
    		if (activity.isNetworkAvailable()) {
    			// AsyncTask subclass
    			new DownloadJsonTask(
    				mListener,
    				mListView,
    				mAdapter,
    				getActivity(),
    				mTab
    			).execute(
    				Utils.addAccessTokenToUrl(mTab.toURL(), mAccessToken)
    			);
    		} else {
    			showErrorPage();
    		}
    	}	
    }
    
    // Displays an error if the app is unable to load content.
    private void showErrorPage() {
    	Activity activity = getActivity();
    	if (activity == null) {
    		return;
    	}
    	// The specified network connection is not available. Displays error message.
        Toast.makeText(
	        activity.getApplicationContext(), 
	        R.string.connection_error, 
	        Toast.LENGTH_SHORT
	    ).show();
    }
}
